package com.atguigu.exer;

import org.junit.Test;

/**
 * 获取一个字符串在另一个字符串出现的次数。
 * 如：获取“ab”在"abakjkjjlkjdsabab"中出现的次数
 */
public class StringDemo1 {
    public int getCount(String mainStr,String subStr ){
        int mainLength = mainStr.length();
        int subLength = subStr.length();
        int count = 0;
        int index = 0;
        if(mainLength >= subLength){
            //方式一：
//            while((index = mainStr.indexOf(subStr)) != -1){
//                count++;
//                mainStr = mainStr.substring(index + subStr.length());
//            }
            //方式二：
            while((index = mainStr.indexOf(subStr,index)) != -1){
                count++;
                index += subStr.length();
            }
            return count;

        }else{
            return 0;
        }
    }

    @Test
    public void test1(){
        String mainStr = "abakjkjjlkjdsabab";
        String subStr = "ab";
        int count = getCount(mainStr, subStr);
        System.out.println(count);

    }
}
